package a_o2odata_deal.utils

import com.alibaba.fastjson.{JSON, JSONObject}
import org.apache.spark.sql.SQLContext
import org.apache.spark.{SparkConf, SparkContext}
import org.elasticsearch.spark._

/**
  * @ Auther: o2o-rd-0008
  * @ Date:   2019/12/7 10:50
  * @ Param:  ${PARAM}
  * @ Description: 
  */
object handle_zhibo_v1 {


  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setAppName(s"${this.getClass.getSimpleName}")
    conf.set("spark.debug.maxToStringFields", "500")
    //conf.setMaster("local[*]")
    conf.set("es.nodes", "192.168.1.157")
    conf.set("es.port", "9200")
    conf.set("cluster.name", "O2OElastic")
    conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
    conf.set("spark.sql.caseSensitive", "true")
    val sc = new SparkContext(conf)
    val sqlContext = new SQLContext(sc)
    sc.setLogLevel("WARN")
    sc.hadoopConfiguration.set("fs.s3a.access.key", "GAO7EO9FWKPJ8WFCQDME")
    sc.hadoopConfiguration.set("fs.s3a.secret.key", "LZ0xaHBSYKHaJ9ECDbX9f7zin79UZkXfGoNapRPL")
    sc.hadoopConfiguration.set("fs.s3a.endpoint", "https://obs.cn-north-1.myhuaweicloud.com")

    /*val zhibo_data = sqlContext.read.json("s3a://o2o-dataproces-group/zhang_feng/create_data/2019_11/meituan/meituan_main_v3/zhibobeifen")
      .drop("viewcount")
    zhibo_data.createOrReplaceTempView("zhibo_data")*/

    val tb_data = sqlContext.read.orc("s3a://dws-data/g_data/2019/11/taobao/")

    //关联直播
    val data_detail = sqlContext.read.json(s"${a_aa_amainpackage.a_o2odata_deal.config.config.tmall_live_detail_path}")
    val data_id = sqlContext.read.json(s"${a_aa_amainpackage.a_o2odata_deal.config.config.tmall_live_id_path}")

    data_id.createOrReplaceTempView("data_id")
    data_detail.createOrReplaceTempView("data_detail")
    //首先统计出单品在多少个直播间出现过

    val mid_data = sqlContext.sql(
      s"""
         |select
         |t1.*,
         |t1.fans as anchorFans,
         |t2.priceText as live_priceText,
         |t2.good_id as good_ids
         |from data_id t1
         |inner join
         |data_detail t2
         |on t1.liveId=t2.liveId
       """.stripMargin).drop("good_id").withColumnRenamed("good_ids","good_id").where("good_id!='-1'")

    mid_data.createOrReplaceTempView("mid_data")

    sqlContext.sql(
      s"""
         |select
         |good_id,
         |anchorId,
         |live_priceText,
         |cast(anchorFans as bigint) as anchorFans,
         |--直播次数
         |sum(cast(liveCount as bigint)) over(partition by good_id) as liveCount,
         |--观看人数
         |sum(cast(viewerCount as bigint)) over(partition by good_id) as viewcount,
         |--直播均价
         |avg(cast(live_priceText as double)) over(partition by good_id) as liveAvgPriceText
         |from mid_data
       """.stripMargin).dropDuplicates("good_id").createOrReplaceTempView("value")

   /* sqlContext.sql(
      s"""
         |select
         |good_id,
         |count(distinct liveId)
         |from mid_data
         |group by good_id
       """.stripMargin)*/

    sqlContext.sql(
      s"""
         |select
         |t1.*,
         |case
         |when t2.userId is null then false
         |else true
         |end as is_selfLive
         |from value t1
         |left join
         |tb_data t2
         |on t1.anchorId=t2.userId
       """.stripMargin).dropDuplicates("good_id").createOrReplaceTempView("data")

    val result = sqlContext.sql(
      s"""
         |select
         |t1.*,
         |cast(t2.live_priceText as double) as live_priceText,
         |cast(t2.liveCount as bigint) as liveCount,
         |cast(t2.viewcount as bigint) as viewcount,
         |cast(t2.liveAvgPriceText as double) as liveAvgPriceText,
         |cast(t2.anchorFans as bigint) as anchorFans,
         |t2.is_selfLive
         |from tb_data t1
         |left join
         |data t2
         |on t1.good_id=t2.good_id
       """.stripMargin)

    val value = result.toJSON.rdd.map(line => {
      val lines = JSON.parseObject(line)
      val evaluates = lines.getOrDefault("evaluates", "-1").toString
      val Base_Info = lines.getOrDefault("Base_Info", "-1").toString
      var promotion_price = lines.getOrDefault("promotion_price","-1").toString
      var original_cost = lines.getOrDefault("original_cost","-1").toString
      val priceText = lines.get("priceText").toString
      if (promotion_price.contains("?") | promotion_price.contains("？")){
        promotion_price = priceText
      }
      if (original_cost.contains("?") | original_cost.contains("？")){
        original_cost = priceText
      }
      var ev = "-1"
      var str = new JSONObject
      if (evaluates.equals("-1")) {
        ev = "{\"fuyi\":\"-1\"}"
      } else {
        str = JSON.parseObject(evaluates)
      }
      if (!ev.contains("fuyi")) {
        lines.put("evaluates", str)
      } else {
        val evs = JSON.parseObject(ev)
        lines.put("evaluates", evs)
      }
      lines.put("Base_Info",Base_Info)
      lines.put("promotion_price",promotion_price)
      lines.put("original_cost",original_cost)
      lines
    })
    //原始代码
    value.saveToEs(s"2019_taobao/taobao_2019_11", Map("es.mapping.id" -> "good_id"))
  }



}
